<template>
  <div>
    <div class="app-container">
      <div class="header-container">
        <h3>商品介绍</h3>
      </div>
      <el-form ref="goods" :rules="rules" :model="goods" label-width="150px">
        <el-form-item :label="$t('goods_edit.form.name')" prop="name">
          <el-input v-model="goods.name" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item :label="$t('goods_edit.form.is_new')" prop="isNew">
          <el-radio-group v-model="goods.isNew">
            <el-radio :label="true">{{
              $t("goods_edit.value.is_new_true")
            }}</el-radio>
            <el-radio :label="false">{{
              $t("goods_edit.value.is_new_false")
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('goods_edit.form.is_hot')" prop="isHot">
          <el-radio-group v-model="goods.isHot">
            <el-radio :label="false">{{
              $t("goods_edit.value.is_hot_false")
            }}</el-radio>
            <el-radio :label="true">{{
              $t("goods_edit.value.is_hot_true")
            }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('goods_edit.form.is_on_sale')" prop="isOnSale">
          <el-radio-group v-model="goods.isOnSale">
            <el-radio :label="true">{{
              $t("goods_edit.value.is_on_sale_true")
            }}</el-radio>
            <el-radio :label="false">{{
              $t("goods_edit.value.is_on_sale_false")
            }}</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item :label="$t('goods_edit.form.pic_url')" prop="picUrl">
          <el-upload
            :action="uploadPath"
            :limit="1"
            :headers="headers"
            :on-exceed="handlePicExceed"
            :on-success="uploadPicUrl"
            :on-remove="handlePicRemove"
            :file-list="picFileList"
            accept=".jpg,.jpeg,.png,.gif"
            list-type="picture-card"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>

        <el-form-item :label="$t('goods_edit.form.gallery')" prop="gallery">
          <el-upload
            :action="uploadPath"
            :limit="5"
            :headers="headers"
            :on-exceed="uploadOverrun"
            :on-success="handleGalleryUrl"
            :on-remove="handleRemove"
            multiple
            accept=".jpg,.jpeg,.png,.gif"
            list-type="picture-card"
            :file-list="galleryFileList"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>

        <el-form-item
          :label="$t('goods_edit.form.category_id')"
          prop="categoryId"
        >
          <el-select
            placeholder="请选择商品分类"
            style="width: 100%"
            v-model="goods.categoryId"
            clearable
          >
            <el-option
              v-for="item in categoryList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('goods_edit.form.keywords')">
          <div class="keywords-container">
            <el-tag
              v-for="tag in keywords"
              :key="tag"
              closable
              type="primary"
              @close="handleClose(tag)"
            >
              {{ tag }}
            </el-tag>
            <el-input
              v-if="newKeywordVisible"
              ref="newKeywordInput"
              v-model="newKeyword"
              class="input-new-keyword"
              @keyup.enter.native="handleInputConfirm"
              @blur="handleInputConfirm"
            />
            <el-button
              v-else
              class="button-new-keyword"
              type="primary"
              @click="showInput"
              >{{ $t("app.button.add") }}</el-button
            >
          </div>
        </el-form-item>

        <el-form-item :label="$t('goods_edit.form.brief')">
          <el-input placeholder="请输入商品简介" v-model="goods.brief" />
        </el-form-item>
      </el-form>
    </div>
    <div class="app-container">
      <h3>{{ $t("goods_edit.section.specifications") }}</h3>
      <div class="spec-section">
        <div class="spec-header">
          <div class="header-left">
            <span class="section-title">商品规格</span>
            <el-radio-group
              v-model="multipleSpec"
              @change="specChanged"
              size="small"
            >
              <el-radio-button :label="false">单规格</el-radio-button>
              <el-radio-button :label="true">多规格</el-radio-button>
            </el-radio-group>
          </div>
          <div v-if="multipleSpec" class="header-right">
            <el-button
              type="primary"
              size="small"
              style="margin-right: 10px;"
              @click="handleAddDefaultRules"
            >快速添加规格</el-button>
            <el-input
              v-model="newSpecName"
              size="small"
              placeholder="输入规格名称"
              class="spec-add-input"
              @keyup.enter.native="handleAddSpecGroup"
            >
              <el-button
                slot="append"
                icon="el-icon-plus"
                @click="handleAddSpecGroup"
                >添加规格</el-button
              >
            </el-input>
          </div>
        </div>

        <!-- 单规格模式 -->
        <div v-if="!multipleSpec" class="single-spec">
          <el-form :model="singleSpecForm" label-width="80px">
            <el-form-item label="销售价格">
              <el-input-number
                v-model="singleSpecForm.price"
                :min="0"
                :precision="2"
                :step="0.1"
                controls-position="right"
                size="small"
                style="width: 160px"
              />
              <span class="unit">元</span>
            </el-form-item>
          </el-form>
        </div>

        <!-- 多规格模式 -->
        <div v-else class="multiple-spec">
          <div class="spec-groups">
            <div
              v-for="(group, groupIndex) in specGroups"
              :key="groupIndex"
              class="spec-group"
            >
              <div>
                <div class="spec-group-header">
                  <div class="spec-name">
                    <span>{{ group.name }}</span>
                  </div>
                  <el-input
                    v-model="group.inputForm.name"
                    size="small"
                    placeholder="输入规格值，如：红色"
                    class="value-input"
                    @keyup.enter.native="handleSpecValueConfirm(groupIndex)"
                  />
                  <el-input-number
                    v-model="group.inputForm.price"
                    :min="0"
                    :precision="2"
                    :step="0.1"
                    size="small"
                    controls-position="right"
                    class="price-input"
                  />
                  <span class="unit">元</span>
                  <el-button
                    type="primary"
                    size="small"
                    icon="el-icon-plus"
                    @click="handleSpecValueConfirm(groupIndex)"
                    >添加</el-button
                  >
                </div>

                <div class="spec-values">
                  <el-tag
                    v-for="(value, valueIndex) in group.values"
                    :key="valueIndex"
                    closable
                    :disable-transitions="false"
                    class="spec-value-tag"
                    @click="handleEditSpecValue(groupIndex, valueIndex)"
                    @close="handleRemoveSpecValue(groupIndex, valueIndex)"
                  >
                    <span class="value-name">{{ value.name }}</span>
                    <span class="value-divider">|</span>
                    <span class="value-price">￥{{ value.price }}</span>
                  </el-tag>
                </div>
              </div>

              <el-button
                type="text"
                class="delete-btn"
                @click="handleRemoveSpecGroup(groupIndex)"
              >
                <i class="el-icon-delete" />
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="op-container">
      <el-button @click="handleCancel">{{ $t("app.button.cancel") }}</el-button>
      <el-button type="primary" @click="handleSubmit">
        {{
          isEdit
            ? $t("goods_edit.button.edit")
            : $t("goods_edit.button.publish")
        }}
      </el-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.app-container {
  margin-bottom: 15px;

  h3 {
    margin: 0 0 15px;
    font-size: 18px;
    font-weight: 500;
    color: #303133;
  }

  .spec-section {
    background: #fff;
    padding: 16px;

    .spec-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;
      padding-bottom: 12px;
      border-bottom: 1px solid #ebeef5;

      .header-left {
        display: flex;
        align-items: center;
        gap: 12px;

        .section-title {
          font-size: 15px;
          font-weight: 500;
          color: #303133;
        }
      }

      .header-right {
        .spec-add-input {
          width: 240px;
        }
      }
    }

    .single-spec {
      padding: 12px 0;

      .unit {
        margin-left: 6px;
        color: #909399;
      }
    }

    .multiple-spec {
      .spec-group {
        margin-bottom: 12px;
        padding: 12px 0;
        border-bottom: 1px solid #ebeef5;
        display: flex;
        align-items: center;

        &:last-child {
          margin-bottom: 0;
          border-bottom: none;
        }

        .delete-btn {
          padding: 2px 4px;
          color: #f56c6c;
          font-size: 25px !important;
          margin-left: auto;

          &:hover {
            background: rgba(245, 108, 108, 0.1);
            border-radius: 3px;
          }

          i {
            font-size: 25px;
          }
        }

        .spec-group-header {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 12px;

          .spec-name {
            display: flex;
            align-items: center;
            gap: 4px;
            min-width: 100px;
            font-weight: 500;
          }

          .value-input {
            width: 240px;
          }

          .price-input {
            width: 100px;
          }

          .unit {
            color: #606266;
            margin: 0 3px;
          }
        }

        .spec-values {
          margin-top: 8px;
          min-height: 32px;
          display: flex;
          flex-wrap: wrap;
          gap: 6px;

          .spec-value-tag {
            display: inline-flex;
            align-items: center;
            height: 28px;
            padding: 0 8px;
            font-size: 12px;
            background: #f5f7fa;
            border-radius: 3px;
            cursor: pointer;
            transition: all 0.2s;

            &:hover {
              background: #ecf5ff;
            }

            .value-name {
              color: #303133;
            }

            .value-divider {
              margin: 0 4px;
              color: #dcdfe6;
            }

            .value-price {
              color: #f56c6c;
              font-weight: 500;
            }

            .el-tag__close {
              margin-left: 4px;

              &:hover {
                color: #f56c6c;
                background: transparent;
              }
            }
          }
        }
      }

      .add-spec-group {
        text-align: center;
        padding: 20px 0;

        .el-button {
          width: 100%;
          height: 44px;
          border: 1px dashed #dcdfe6;
          color: #409eff;
          font-size: 14px;

          &:hover {
            border-color: #409eff;
            color: #409eff;
            background: rgba(64, 158, 255, 0.1);
          }

          i {
            margin-right: 4px;
          }
        }
      }
    }
  }
}

.spec-value-popover {
  .value-form {
    padding: 12px;

    .form-item {
      margin-bottom: 16px;
      display: flex;
      align-items: center;

      .label {
        width: 70px;
        color: #606266;
      }

      .unit {
        margin-left: 8px;
        color: #909399;
      }
    }

    .form-footer {
      text-align: right;
      margin-top: 20px;
      padding-top: 16px;
      border-top: 1px solid #ebeef5;
    }
  }
}

.el-form {
  width: 800px;
}

.keywords-container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 8px;
}

.op-container {
  display: flex;
  justify-content: center;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 145px;
  height: 145px;
  display: block;
}
</style>

<script>
import {
  publishGoods,
  listCatAndBrand,
  detailGoods,
  editGoods,
} from "@/api/goods";
import { createStorage, uploadPath } from "@/api/storage";
import { MessageBox } from "element-ui";
import { getToken } from "@/utils/auth";

export default {
  name: "GoodsCreate",
  components: {},
  data() {
    return {
      uploadPath,
      isEdit: false,
      newKeywordVisible: false,
      newKeyword: "",
      keywords: [],
      picFileList: [], // 商品主图文件列表
      galleryFileList: [],
      categoryList: [],
      brandList: [],
      goods: {
        picUrl: "",
        gallery: [],
        isHot: false,
        isNew: true,
        isOnSale: true,
        categoryId: undefined,
      },
      multipleSpec: false,
      specGroups: [],
      singleSpecForm: {
        price: 0,
      },
      newSpecName: "",
      rules: {
        name: [
          { required: true, message: "商品名称不能为空", trigger: "blur" },
        ],
        picUrl: [
          { required: true, message: "请上传商品图片", trigger: "change" },
        ],
        categoryId: [
          { required: true, message: "请选择商品分类", trigger: "change" },
        ],
        gallery: [
          { required: true, message: "请上传商品画廊图片", trigger: "change" },
        ],
        isNew: [
          { required: true, message: "请选择是否新品", trigger: "change" },
        ],
        isHot: [
          { required: true, message: "请选择是否热卖", trigger: "change" },
        ],
        isOnSale: [
          { required: true, message: "请选择是否上架", trigger: "change" },
        ],
      },
    };
  },
  computed: {
    headers() {
      return {
        "X-Litemall-Admin-Token": getToken(),
      };
    },
  },
  created() {
    this.init();
  },

  methods: {
    init: function () {
      // 获取分类和品牌列表
      listCatAndBrand().then((response) => {
        this.categoryList = response.data.data.categoryList;
        this.brandList = response.data.data.brandList;
      });

      // 如果有ID参数，说明是编辑模式
      const goodsId = this.$route.query.id;
      if (goodsId != null) {
        this.isEdit = true;
        detailGoods(goodsId).then((response) => {
          const { goods, specifications } = response.data.data;

          // 设置商品基本信息
          this.goods = goods;

          // 设置商品主图
          if (this.goods.picUrl) {
            this.picFileList = [
              {
                url: this.goods.picUrl,
              },
            ];
          }

          // 设置商品画廊
          this.galleryFileList = [];
          for (var i = 0; i < this.goods.gallery.length; i++) {
            this.galleryFileList.push({
              url: this.goods.gallery[i],
            });
          }

          // 设置关键词
          if (goods.keywords) {
            this.keywords = goods.keywords.split(",");
          }

          // 根据接口返回的 isMultipleSpec 字段判断规格类型
          this.multipleSpec = goods.isMultipleSpec || false;

          if (this.multipleSpec) {
            // 多规格模式
            const specGroups = {};
            specifications.forEach((spec) => {
              if (!specGroups[spec.specification]) {
                specGroups[spec.specification] = {
                  name: spec.specification,
                  values: [],
                  inputForm: {
                    name: "",
                    price: 0,
                  },
                };
              }
              specGroups[spec.specification].values.push({
                name: spec.value,
                price: spec.price,
              });
            });

            this.specGroups = Object.values(specGroups);
          } else {
            // 单规格模式
            this.singleSpecForm = {
              price: goods.retailPrice || 0,
            };
          }
        });
      }
    },
    handleCategoryChange(value) {
      this.goods.categoryId = value[value.length - 1];
    },
    handleCancel: function () {
      this.$store.dispatch("tagsView/delView", this.$route);
      this.$router.push({ path: "/goods/list" });
    },
    handleSubmit() {
      this.$refs.goods.validate((valid) => {
        if (!valid) {
          this.$message.error("请填写完整信息");
          return;
        }

        // 验证规格信息
        if (!this.validateSpecs()) {
          return;
        }

        const finalGoods = {
          goods: {
            ...this.goods,
            isMultipleSpec: this.multipleSpec, // 添加规格模式标识
            retailPrice: this.multipleSpec
              ? this.calculateMinPrice()
              : this.singleSpecForm.price, // 多规格时计算最低价格
          },
          specifications: this.generateSpecifications(),
        };

        const submitAction = this.isEdit ? editGoods : publishGoods;
        const successMessage = this.isEdit ? "编辑成功" : "创建成功";

        submitAction(finalGoods)
          .then((response) => {
            this.$message.success({
              title: "成功",
              message: successMessage,
            });
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.push({ path: "/goods/list" });
          })
          .catch((response) => {
            MessageBox.alert("业务错误：" + response.data.errmsg, "警告", {
              confirmButtonText: "确定",
              type: "error",
            });
          });
      });
    },
    handleClose(tag) {
      this.keywords.splice(this.keywords.indexOf(tag), 1);
      this.goods.keywords = this.keywords.toString();
    },
    showInput() {
      this.newKeywordVisible = true;
      this.$nextTick((_) => {
        this.$refs.newKeywordInput.$refs.input.focus();
      });
    },
    handleInputConfirm() {
      const newKeyword = this.newKeyword;
      if (newKeyword) {
        this.keywords.push(newKeyword);
        this.goods.keywords = this.keywords.toString();
      }
      this.newKeywordVisible = false;
      this.newKeyword = "";
    },
    uploadPicUrl(response) {
      if (response.errno === 0) {
        this.goods.picUrl = response.data.url;
      }
    },
    handlePicExceed() {
      this.$message({
        type: "error",
        message: "只能上传一张商品主图!",
      });
    },
    handlePicRemove() {
      this.goods.picUrl = "";
      this.picFileList = [];
    },
    uploadOverrun: function () {
      this.$message({
        type: "error",
        message: "上传文件个数超出限制!最多上传5张图片!",
      });
    },
    handleGalleryUrl(response, file, fileList) {
      if (response.errno === 0) {
        this.goods.gallery.push(response.data.url);
      }
    },
    handleRemove: function (file, fileList) {
      for (var i = 0; i < this.goods.gallery.length; i++) {
        // 这里存在两种情况
        // 1. 如果所删除图片是刚刚上传的图片，那么图片地址是file.response.data.url
        //    此时的file.url虽然存在，但是是本机地址，而不是远程地址。
        // 2. 如果所删除图片是后台返回的已有图片，那么图片地址是file.url
        var url;
        if (file.response === undefined) {
          url = file.url;
        } else {
          url = file.response.data.url;
        }

        if (this.goods.gallery[i] === url) {
          this.goods.gallery.splice(i, 1);
        }
      }
    },
    specChanged(value) {
      if (value) {
        // 切换到多规格时，初始化为空数组
        this.specGroups = [];
      } else {
        this.singleSpecForm = {
          price: 0,
        };
      }
    },
    handleAddSpecGroup() {
      if (!this.newSpecName.trim()) {
        this.$message.warning("请输入规格名称");
        return;
      }

      this.specGroups.push({
        name: this.newSpecName.trim(),
        values: [],
        popoverVisible: false,
        inputForm: {
          name: "",
          price: 0,
        },
      });

      this.newSpecName = ""; // 清空输入
    },
    handleAddDefaultRules() {
      // 设置为多规格模式
      this.multipleSpec = true;
      
      // 添加尺寸规格
      this.specGroups.push({
        name: "尺寸",
        values: [
          { name: "八寸", price: 0.01 },
          { name: "十寸", price: 0.02 }
        ],
        popoverVisible: false,
        inputForm: {
          name: "",
          price: 0,
        },
      });

      // 添加奶油规格
      this.specGroups.push({
        name: "奶油",
        values: [
          { name: "植物奶油", price: 0.01 },
          { name: "动物奶油", price: 0.02 }
        ],
        popoverVisible: false,
        inputForm: {
          name: "",
          price: 0,
        },
      });

      this.$message.success("已添加默认规则");
    },
    handleSpecValueConfirm(groupIndex) {
      const group = this.specGroups[groupIndex];
      const { name, price } = group.inputForm;

      if (name.trim()) {
        group.values.push({
          name: name.trim(),
          price,
        });

        // 重置输入表单
        group.inputForm = {
          name: "",
          price: 0,
        };
        group.popoverVisible = false;
      }
    },
    handleRemoveSpecGroup(index) {
      this.specGroups.splice(index, 1);
    },
    handleRemoveSpecValue(groupIndex, valueIndex) {
      this.specGroups[groupIndex].values.splice(valueIndex, 1);
    },
    handleEditSpecValue(groupIndex, valueIndex) {
      const group = this.specGroups[groupIndex];
      const value = group.values[valueIndex];

      // 将值复制到输入表单中进行编辑
      group.inputForm = {
        name: value.name,
        price: value.price,
      };

      // 删除原来的值
      group.values.splice(valueIndex, 1);
    },
    generateSpecifications() {
      if (!this.multipleSpec) {
        // 单规格模式下，只传递一个标准规格和价格
        return [
          {
            specification: "规格",
            value: "标准",
            price: this.singleSpecForm.price,
            isMultipleSpec: false,
          },
        ];
      }

      // 多规格模式下，传递所有规格组和对应的值
      const specs = [];
      this.specGroups.forEach((group) => {
        group.values.forEach((value) => {
          specs.push({
            specification: group.name,
            value: value.name,
            price: value.price,
            isMultipleSpec: true,
          });
        });
      });

      return specs;
    },
    // 计算多规格最低价格
    calculateMinPrice() {
      if (!this.multipleSpec || this.specGroups.length === 0) {
        return this.singleSpecForm.price;
      }
      
      let totalMinPrice = 0;
      
      // 遍历每个规格组，找出每组中价格最低的规格值
      this.specGroups.forEach(group => {
        if (group.values && group.values.length > 0) {
          // 找出当前规格组中价格最低的值
          const minPrice = Math.min(...group.values.map(v => v.price));
          totalMinPrice += minPrice;
        }
      });
      
      return totalMinPrice;
    },
    // 验证规格表单
    validateSpecs() {
      if (!this.multipleSpec) {
        return true;
      }

      // 检查是否有规格组
      if (this.specGroups.length === 0) {
        this.$message.error("请至少添加一个规格");
        return false;
      }

      // 检查每个规格组
      for (let i = 0; i < this.specGroups.length; i++) {
        const group = this.specGroups[i];

        // 检查规格名称
        if (!group.name.trim()) {
          this.$message.error("请填写规格名称");
          return false;
        }

        // 检查规格值
        if (group.values.length === 0) {
          this.$message.error(`请为规格 "${group.name}" 添加至少一个规格值`);
          return false;
        }

        // 检查规格值的名称和价格
        for (let j = 0; j < group.values.length; j++) {
          const value = group.values[j];
          if (!value.name.trim()) {
            this.$message.error("规格值名称不能为空");
            return false;
          }
          if (value.price < 0) {
            this.$message.error("规格值价格不能小于0");
            return false;
          }
        }
      }

      return true;
    },
    goBack() {
      this.$router.go(-1);
    },
  },
};
</script>
